/* eslint-disable @typescript-eslint/no-require-imports */

const path = require('path');
const fs = require('fs');

const fileExists = (filepath) => {
  try {
    return fs.statSync(filepath).isFile();
  } catch (e) {
    return false;
  }
};

module.exports = ({ onGetWebpackConfig, context, modifyUserConfig }) => {
  const { command } = context;

  modifyUserConfig((originConfig) => {
    const rootPath = path.resolve(__dirname, '.');
    const configFile = path.join(rootPath, 'config.local.js');

    let config = originConfig;

    if (fileExists(configFile)) {
      config = require(configFile)(originConfig, { command, mode: 'production' });
    }

    return config;
  });

  onGetWebpackConfig((config) => {
    if (command === 'start') {
      config.devServer.writeToDisk(false);
    }

    config
      .plugin('env')
      .use(require.resolve('webpack/lib/EnvironmentPlugin'), [
        { MODE: 'prod' },
      ]);
  });
};
